package com.gaohe.common.utils.file;

/**
 * @ClassName MinioUtil
 * @Description minio
 * @Author yunxiaoleng
 * @Date 2024/7/12 8:54
 * @Version 1.0
 **/

import com.gaohe.common.utils.spring.SpringUtils;
import io.minio.*;
import io.minio.http.Method;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/** 初始化了连接方法,及桶权限获取*/
public class MinioUtil {
    /**
     * @param bucketName 桶名称
     * @param fileName
     * @throws IOException
     */
    public static String uploadFile(String bucketName, String fileName, MultipartFile multipartFile) throws IOException
    {
        String url = "";
        MinioClient minioClient = SpringUtils.getBean(MinioClient.class);
        try (InputStream inputStream = multipartFile.getInputStream()) {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found)
            {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                /**
                 * bucket权限-读写
                 */
                String READ_WRITE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(READ_WRITE).build());
            }
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                    .object(fileName)
                    .stream(inputStream, multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType()).build()
            );
            //路径获取
            url = "/" + bucketName+ "/" + fileName;
            //常规访问路径获取
            return url;
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }
}

